import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Space,
  Input,
  Radio,
  Upload,
  Modal,
  message,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom'
import Channel from 'components/Channel'
import ReactQuill from 'react-quill' //富文本编辑器
import 'react-quill/dist/quill.snow.css'
import styles from './index.module.scss'
import { baseURL } from 'utils/request'
import { addArticles, getArticleById, editArticle } from 'api/article'
export default class publish extends Component {
  state = {
    // 存放上传的文件列表
    fileList: [],
    type: 0,
    previewVisible: false,
    url: '',
    id: this.props.match.params.id, //编辑文章的id
  }
  formRef = React.createRef()
  render() {
    return (
      <div className={styles.publish}>
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                {this.state.id ? '编辑文章' : '发布文章'}
              </Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            ref={this.formRef}
            onFinish={this.onFinish}
            labelCol={{ span: 4 }}
            initialValues={{ content: '', type: this.state.type }}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '文章标题不能为空' }]}
            >
              <Input
                style={{ width: 400 }}
                placeholder="请输入文章标题"
              ></Input>
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '频道不能为空' }]}
            >
              <Channel></Channel>
            </Form.Item>
            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.changeImageType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              {this.state.type !== 0 && (
                <Upload
                  beforeUpload={this.handleBeforeUpload}
                  onPreview={this.handlePreview}
                  onChange={this.uploadImages}
                  action={`${baseURL}upload`}
                  listType="picture-card"
                  name="image"
                  fileList={this.state.fileList}
                >
                  {this.state.fileList.length < this.state.type && (
                    <PlusOutlined></PlusOutlined>
                  )}
                </Upload>
              )}
              <Modal
                visible={this.state.previewVisible}
                title={'图片预览'}
                footer={null}
                onCancel={this.handleCancel}
              >
                <img
                  alt="example"
                  style={{ width: '100%' }}
                  src={this.state.url}
                />
              </Modal>
            </Form.Item>
            <Form.Item label="内容" name="content">
              <ReactQuill
                theme="snow"
                placeholder="请输入文章内容..."
              ></ReactQuill>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit">
                  {this.state.id ? '编辑文章' : '发布文章'}
                </Button>
                <Button size="large" type="primary" onClick={this.draftClick}>
                  存入草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
  async componentDidMount() {
    if (this.state.id) {
      const res = await getArticleById(this.state.id)
      // console.log(res)
      const values = { ...res.data, type: res.data.cover.type }
      //数据回显
      this.formRef.current.setFieldsValue(values)
      //封面图像回显
      const fileList = res.data.cover.images.map((item) => {
        return { url: item }
      })
      this.setState({
        type: res.data.cover.type,
        fileList,
      })
    }
  }
  //添加草稿
  draftClick = async () => {
    const values = await this.formRef.current.validateFields()
    // console.log(value)
    this.save(values, true)
  }
  handleBeforeUpload = (file) => {
    // console.log(file)
    if (file.size > 1024 * 500) {
      message.warning('上传的文件不能超过500kb')
      return Upload.LIST_IGNORE
    }
    if (!['image/png', 'image/jpeg'].includes(file.type)) {
      message.warning('只能上传jpeg或者png的图片')
      return Upload.LIST_IGNORE
    }
  }
  handleCancel = () => {
    this.setState({
      previewVisible: false,
      url: '',
    })
  }
  handlePreview = (e) => {
    // console.log(e)
    this.setState({
      previewVisible: true,
      url: e.url || e.response.data.url,
    })
  }
  changeImageType = (e) => {
    // console.log(e)
    this.setState({
      type: e.target.value,
    })
  }
  uploadImages = (e) => {
    console.log(e)
    this.setState({
      fileList: e.fileList,
    })
  }
  onFinish = (values) => {
    // console.log(values)
    this.save(values, false)
  }
  async save(values, draft) {
    if (this.state.fileList.length !== this.state.type) {
      return message.warning('图片数量不符合')
    }
    const images = this.state.fileList.map((item) => {
      return item.url || item.response.data.url
    })
    if (this.state.id) {
      // 修改文章
      await editArticle(
        {
          ...values,
          cover: {
            type: values.type,
            images,
          },
          id: this.state.id,
        },
        draft
      )
      message.success('修改文章成功')
      this.props.history.push('/home/list')
    } else {
      //添加文章
      await addArticles(
        {
          ...values,
          cover: {
            type: values.type,
            images,
          },
        },
        draft
      )
      message.success('添加文章成功')
      this.props.history.push('/home/list')
    }
  }
}
